package com.hirsi.core.expand;

import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.*;

public interface TreeNode<T, ID> {

    static <E extends TreeNode> List<E> toTreeList(Collection<E> source) {
        if (source.size() < 2) return new ArrayList<>(source);
        List<E> result = new ArrayList<>();
        Map<Object, E> map = new HashMap<>();
        for (E e : source) {
            Object id = e.getNodeId();
            map.put(id, e);
        }
        for(E e : source) {
            Object pid = e.getParentNodeId();
            E parentNode = null;
            if (pid != null && (pid instanceof Integer && (Integer) pid != 0)) {
                parentNode = map.get(pid);
            }
            if (parentNode == null) {
                result.add(e);
            } else {
                if (parentNode.getChildren() == null) parentNode.setChildren(new ArrayList());
                parentNode.getChildren().add(e);
            }
        }
        return result;
    }

    @JsonIgnore
    ID getNodeId();

    @JsonIgnore
    ID getParentNodeId();

    List<T> getChildren();

    void setChildren(List<T> children);
}
